package com.ruge.common.exception;

import com.google.gson.Gson;
import com.ruge.common.util.RestResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;

/**
 * 创建人 ：爱丽丝、如歌
 * 创建时间 ：2020-03-04  18:13
 * 描述 ：
 */
@ControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler({HttpMessageNotReadableException.class,
            HttpRequestMethodNotSupportedException.class,
            HttpMediaTypeNotSupportedException.class,
            SQLException.class})
    public void handleHttpMessageNotReadableException(HttpServletRequest request,
                                                      HttpServletResponse response,
                                                      Exception e){

        RestResponse restResponse = RestResponse.failure(e.getMessage());
        Gson gson = new Gson();
        try {
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter writer = response.getWriter();
            writer.write(gson.toJson(restResponse));
            writer.flush();
            writer.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
}
